package com.example.ioc.service.impl;

import com.example.ioc.annotation.Transaction;
import com.example.ioc.mapper.AccountMapper;
import com.example.ioc.mapper.impl.AccountMapperImpl;
import com.example.ioc.pojo.Account;
import com.example.ioc.service.TransferService;
import com.example.spring.framework.annotation.Autowired;
import com.example.spring.framework.annotation.Service;

/**
 * @author admin
 * @Date 2021/1/4 23:20
 * @Description TODO
 */
@Service
public class TransferServiceImpl implements TransferService {


    // 最佳状态
    // @Autowired 按照类型注入 ,如果按照类型无法唯一锁定对象，可以结合@Qualifier指定具体的id
    @Autowired
    private AccountMapper accountMapper;


    @Transaction
    @Override
    public void transfer(String fromCardNo, String toCardNo, int money) throws Exception {

        /*try{
            // 开启事务(关闭事务的自动提交)
            TransactionManager.getInstance().beginTransaction();*/
        if (accountMapper == null) {
            accountMapper = new AccountMapperImpl();
        }

        Account from = accountMapper.queryAccountByCardNo(fromCardNo);
        Account to = accountMapper.queryAccountByCardNo(toCardNo);

        from.setMoney(from.getMoney() - money);
        to.setMoney(to.getMoney() + money);

        accountMapper.updateAccountByCardNo(to);
        accountMapper.updateAccountByCardNo(from);


        // 模拟异常
        from = accountMapper.queryAccountByCardNo(fromCardNo);
        if (from.getMoney() < 0) {
            throw new RuntimeException("钱不够啦");
        }


    }
}
